package org.linlinjava.litemall.admin.web.merchant;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.util.Websocket;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallShopBalance;
import org.linlinjava.litemall.db.domain.LitemallShopSetting;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallShopBalanceService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.service.LitemallShopSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/admin/merchant/shop")
@Validated
public class MerchantShopController {
    private final Log logger = LogFactory.getLog(MerchantShopController.class);

    @Autowired
    private LitemallShopService shopService;
    @Autowired
    private LitemallShopSettingService shopSettingService;
    @Autowired
    private LitemallShopBalanceService shopBalanceService;
    @Autowired
    private StorageService storageService;

    @RequiresPermissions("admin:merchant_shop:list")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "商家店铺管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String name, String shopPhone, String shopName,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
    	LitemallAdmin admin = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
        List<LitemallShop> ShopList = shopService.merchant_querySelective(admin, name, shopPhone, shopName, page, limit);
        return ResponseUtil.okList(ShopList);
    }

    private Object validate(LitemallShop shop) {
        String ShopName = shop.getShopName();
        if (StringUtils.isEmpty(ShopName)) {
            return ResponseUtil.badArgument();
        }
        String address = shop.getShopAddress();
        if (StringUtils.isEmpty(address)) {
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:merchant_shop:create")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "商家店铺管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody LitemallShop shop) {
    	//先查询是否已创建有店铺
    	LitemallAdmin admin = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
    	if(admin.getShopId() == 0) { //未创建店铺 shopid为0
            shopService.add(shop,admin);
    	}
        return ResponseUtil.ok(shop);
    }

    @RequiresPermissions("admin:merchant_shop:update")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "商家店铺管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallShop shop) throws IOException {
        Object error = validate(shop);
        if (error != null) {
            return error;
        }
        if (shopService.updateById(shop) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        Websocket.sendtoUser("通知","11");

        return ResponseUtil.ok(shop);
    }
    
    @RequiresPermissions("admin:merchant_shop:updateShopOff")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "商家店铺管理"}, button = "店铺开关")
    @PostMapping("/updateShopOff")
    public Object updateShopOff(@RequestBody LitemallShop shop) {
    	if(shop.getId() == null) {
    		return ResponseUtil.badArgument();
    	}
    	//先查询店铺是否设置有费率、以及店铺基本的设置
    	//查询 litemall_shop_setting 表 如果根据店铺id查询有数据 说明设置过
    	LitemallShopSetting shopSetting = shopSettingService.getOneByShopId(shop.getId());
    	if(shopSetting == null) {
    		return ResponseUtil.custom("请先设置店铺信息！");
    	}

        if (shopService.updateById(shop) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(shop);
    }

    @RequiresPermissions("admin:merchant_shop:delete")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "商家店铺管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallShop shop) {
        Integer id = shop.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        shopService.delShop(shop);
        return ResponseUtil.ok();
    }
    
    @RequiresPermissions("admin:merchant_shop:shopIncome")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "门店收入"}, button = "查询")
    @GetMapping("shopIncome")
    public Object shopIncome(String name, String shopPhone, String shopName,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        return ResponseUtil.okList(shopBalanceService.querySelective(name, shopPhone, shopName, page, limit));
    }
    
    @RequiresPermissions("admin:merchant_shop:upload")
    @RequiresPermissionsDesc(menu = {"商家店铺管理", "图片上传"}, button = "上传")
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        LitemallStorage litemallStorage = storageService.store(file.getInputStream(), file.getSize(),
                file.getContentType(), originalFilename);
        return ResponseUtil.ok(litemallStorage);
    }
}
